package com.gopay.common.cps.send.impl;

import java.net.InetSocketAddress;

import javax.annotation.Resource;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoConnector;

import com.gopay.common.account.AccountResult;
import com.gopay.common.cps.send.Account;
import com.gopay.common.domain.acps.TranInfoBean;
import com.gopay.common.util.JsonUtils;

public class AccountImpl implements Account {
    /**
     * 服务端地址
     */
    protected String ip;

    /**
     * 端口
     */
    protected int port;

    /**
     * 发送系统
     */
    protected String from;

    @Resource(name = "nioSocketConnector")
    private IoConnector nioSocketConnector;

    @Override
    public AccountResult enterAcct(TranInfoBean transInfo) {
        AccountResult result = new AccountResult();

        try {
            ConnectFuture future = nioSocketConnector.connect(new InetSocketAddress(ip, port));
            // 同步调用
            future.awaitUninterruptibly();
            WriteFuture  writeFuture = future.getSession().write(JsonUtils.toJson(transInfo));
            writeFuture.awaitUninterruptibly();
            future.getSession().close(true);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void setFrom(String from) {
        this.from = from;
    }

}
